<?php 
require_once 'common/common.inc.php';

if (isset($_REQUEST["name1"])) {

  $replace = array("","","","");
  $search = array("voornaam","achternaam","email","e-mail");

  $name1 = trim(str_ireplace($search,$replace,$_REQUEST["name1"]));
  $name2 = trim(str_ireplace($search,$replace,$_REQUEST["name2"]));
  $gender = isset($_REQUEST["gender"]) ? $_REQUEST["gender"] : null;

  // open db
  conn();
      
  // save name      
  $sqlCustomers = "SELECT ID FROM CUSTOMERS WHERE UPPER(EMAIL) = UPPER('$email') ";
  $result = mysql_query($sqlCustomers);
  if (!$result) {die('Could not exec query sqlCustomers: ' . mysql_error());}
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  if (isset($row["ID"]) && $row["ID"] != null) 
  {
    $customerId = $row["ID"];
    $sqlUpdateCustomers = "UPDATE CUSTOMERS ";
    $sqlUpdateCustomers .= "SET NAME1 = '$name1', NAME2 = '$name2', EMAIL = '$email', GENDER = '$gender' ";
    $sqlUpdateCustomers .= "WHERE ID = '$customerId' ";
    //echo $sqlUpdateCustomers;
    $result = mysql_query($sqlUpdateCustomers);
    if (!$result) {	die('Could not exec query sqlUpdateCustomers: ' . mysql_error()); } else { $success = true; }
  } 
  else 
  {
    $sqlInsertCustomers = "INSERT INTO CUSTOMERS(NAME1, NAME2, EMAIL, GENDER) ";
    $sqlInsertCustomers .= "VALUES ('".mysql_escape($name1)."', '".mysql_escape($name2)."', '".mysql_escape($email)."', '$gender') ";
    $result = mysql_query($sqlInsertCustomers);
    if (!$result) {	die('Could not exec query sqlInsertCustomers: ' . mysql_error()); } else { $success = true; }
    $customerId = mysql_insert_id();
  }
  
  // close db  
  close();
  
  if ($success) 
  {
    $_SESSION["NAME1"] = $name1;
    $_SESSION["NAME2"] = $name2;
    $_SESSION["GENDER"] = $gender;
    
    //echo $sqlCustomers;
    if (isset($name1) && $name1 != null) { echo $name1." (".$email.") "; } else { echo $email;} 

    //header( 'Location: 02_datetime_picker.php?showNameDialog=0' ) ;
    //die;
  } 
  else 
  {
    $error = $generalErrorMessage;
  }    

}
  
?>